package com.atguigu.gmall.order.mq;


import com.atguigu.gmall.common.constant.RabbitConstant;
import com.atguigu.gmall.common.util.JsonUtils;
import com.atguigu.gmall.model.mq.SeckillOrderMsg;
import com.atguigu.gmall.order.biz.service.OrderSeckillService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class OrderSeckillListener {


    @Autowired
    OrderSeckillService orderSeckillService;

    @RabbitListener(queues = RabbitConstant.ORDER_SECKILL_QUEUE)
    public void listenDeadOrder(Channel channel, Message message){
        long tag = message.getMessageProperties().getDeliveryTag();
        try {
            //处理业务
            SeckillOrderMsg msg = JsonUtils.converMessageToObject(message, new TypeReference<SeckillOrderMsg>() {
            });

            //准备一个秒杀的订单；
            orderSeckillService.prepareSeckillOrder(msg);
            channel.basicAck(tag,false);
        }catch (Exception e){
            log.error("秒杀单处理失败：{}",e);
            try {
                channel.basicReject(tag,true);
            } catch (IOException ex) {
                log.error("MQ连接错误：{}",ex);
            }
        }

    }
}
